package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserOrderDetailsMapper;
import com.sky.mapper.UserOrdersMapper;
import com.sky.result.PageResult;
import com.sky.service.UserOrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 星河一叶Ck
 * @date 2024/10/6
 */

@Service
public class UserOrderServiceImpl implements UserOrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserOrdersMapper userOrdersMapper;
    @Autowired
    private UserOrderDetailsMapper userOrderDetailsMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    // 开启事务 不然可能发生订单生成 但是订单明细错误 却没生成的一个订单无回滚的bug
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 处理业务异常(地址簿为空、购物车为空)
        AddressBook addressBook = addressBookMapper.getAddressById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null) {
            // 抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());

        Long userId = BaseContext.getCurrentId();

        // 查询购物车
        ShoppingCart shoppingCart = new ShoppingCart();
        // 查询当前登录用户的购物车内容
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if(shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 生成一个订单
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        // 首先生成订单后 一开始未支付
        orders.setPayStatus(Orders.UN_PAID);
        // 订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        // 收货人
        orders.setConsignee(addressBook.getConsignee());
        // 订单号生成 (name + UUID)
        orders.setNumber("Ck-" + UUID.randomUUID());
        // 手机号
        orders.setPhone(addressBook.getPhone());
        // 下单时间
        orders.setOrderTime(LocalDateTime.now());
        // 用户id绑定
        orders.setUserId(userId);
        // 地址
//        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        // 字符串拼接进行优化一下
        StringBuilder sb = new StringBuilder();
        sb.append(addressBook.getProvinceName())
                .append(addressBook.getCityName())
                .append(addressBook.getDistrictName())
                .append(addressBook.getDetail());
        orders.setAddress(sb.toString());
        // 插入订单
        userOrdersMapper.insert(orders);

        // 这里我们一次性插入 所以用一个数组装
        List<OrderDetail> orderDetailList = new ArrayList<>();
        // 购物车的每一个商品放入到订单明细中
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }

        // 这里一次性插入
        userOrderDetailsMapper.insertBatch(orderDetailList);

        // 清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        // 封装成VO 然后进行返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userOrdersMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "星河一叶外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        // 为替代微信支付成功后数据库订单状态更新,多定义一个方法进行修改
        Integer OrderPaidStatus = Orders.PAID; // 支付状态,已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED; // 订单状态,待接单

        // 发现没有将支付时间 check_out属性赋值,所以在这里更新
        LocalDateTime check_out_time = LocalDateTime.now();

        // 获取订单号码
        String orderNumber = ordersPaymentDTO.getOrderNumber();

//        log.info("调用updateStatus,用于替换微信支付更新数据库状态的问题");
        userOrdersMapper.updateStatus(OrderStatus,OrderPaidStatus,check_out_time,orderNumber);

        Orders orders = userOrdersMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        // 通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type",1); // 1: 来单提醒 2: 催单
        map.put("orderId",orders.getId());
        map.put("content","订单号: " + orders.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = userOrdersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        userOrdersMapper.update(orders);


    }

    /**
     * 分页查询历史订单
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQueryOrder(int pageNum, int pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = userOrdersMapper.pageQuery(ordersPageQueryDTO);

        // 保存每一份的 订单 + 订单明细
        List<OrderVO> orderVOList = new ArrayList<>();
        // page保存都所有的order
        if(page != null && page.getTotal() > 0) {
            for (Orders order : page) {
                Long orderId = order.getId();

                // 查询订单明细
                List<OrderDetail> orderDetailList = userOrdersMapper.getOrderDetailsByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order,orderVO);
                orderVO.setOrderDetailList(orderDetailList);

                orderVOList.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(),orderVOList);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    public OrderVO getOrderVOById(Long id) {
        // 这里不用用户id进行二次确认是因为id是主键 是唯一标识且不重复
        Orders orders = userOrdersMapper.getOrdersById(id);

        List<OrderDetail> orderDetailList = userOrdersMapper.getOrderDetailsByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    public void cancelOrder(Long id) throws Exception {
//        首先查看该订单是否存在
        Orders orders = userOrdersMapper.getOrdersById(id);

        if(orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        // 如果是待付款或者待接单 可以直接退款 但是其他的需要和商家沟通
        if(orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders order = new Orders();
        order.setId(orders.getId());

        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            // 如果是待接单状态取消 需要进行退款
            // 因为未支付 所以微信退款直接跳过
            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    orders.getNumber(), //商户订单号
//                    orders.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        userOrdersMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    public void repeatOrder(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询订单详情
        List<OrderDetail> orderDetailList = userOrderDetailsMapper.getByOrderId(id);

        // 将查询到的菜品 都重新放入到购物车中
        List<ShoppingCart> shoppingCartList = orderDetailList.stream()
                .map(x -> {
                    ShoppingCart shoppingCart = new ShoppingCart();

                    // 将原订单详情里面的菜品信息重新复制到购物车对象中
                    // 这里是与之对应的订单id
                    BeanUtils.copyProperties(x,shoppingCart,"id");
                    shoppingCart.setUserId(userId);
                    shoppingCart.setCreateTime(LocalDateTime.now());

                    return shoppingCart;
                }).collect(Collectors.toList());

        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 客户催单
     * @param id
     */
    public void remindOrder(Long id) {
        // 根据订单id查询订单并且校验订单是否存在
        Orders orders = userOrdersMapper.getOrdersById(id);

        if(orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap();
        map.put("type",2); // 1: 来单提醒 2: 客户催单
        map.put("orderId",id);
        map.put("content","订单号: " + orders.getNumber());

        // 通过websocket向客户端浏览器推送消息
//        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map<String,String> map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        // 数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        // 店铺经纬度坐标
        String shopLngLag = lat + ',' + lng;

        map.put("address",address);
        // 获取用户收获地址经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        // 数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        String userLngLag = lat + "," + lng;

        map.put("origin",shopLngLag);
        map.put("destination",userLngLag);
        map.put("steps_info","0");

        // 路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        // 数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 999999999) {
            // 配送距离超过5km  临时:999999999km
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
